//  this library.
import 'dart:async';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluwx/fluwx.dart';
import 'package:hktk_app/dao/package_dao.dart';
import 'package:hktk_app/exception/dao_exception.dart';
import 'package:hktk_app/ienum/package/payment_type_enum.dart';
import 'package:hktk_app/model/package/order_model.dart';
import 'package:hktk_app/model/package/package_model.dart';
import 'package:hktk_app/pages/package/pay_success_page.dart';
import 'package:hktk_app/util/buy_ios_util.dart';
import 'package:hktk_app/util/font_util.dart';
import 'package:hktk_app/util/toast_util.dart';
import 'package:hktk_app/util/view_util.dart';
import 'package:hktk_app/widget/package/order_type_widget.dart';
import 'package:hktk_app/widget/package/package_card_widget.dart';
import 'package:hktk_app/widget/page_title_widget.dart';
import 'package:hktk_app/widget/show_label_widget.dart';
import 'package:tobias/tobias.dart';

/// 自定义方法
typedef FlutterPayFun = Future<Map<String, dynamic>> Function({
required DeviceTypeEnum deviceTypeEnum,
});

/// 订单支付页面,如果是继续订单支付呢
class OrderPaymentPage extends StatefulWidget {
  /// 卡片相关信息
  final PackageModel package;

  /// 订单相关信息
  final OrderModel orderModel;

  /// 当前卡片对应下标
  final int index;

  /// 支付价格
  final double price;

  /// iOS阶梯支付价格
  final double iosPrice;

  /// 是否隐藏支付方式（微信/支付宝）,true：隐藏，false：不隐藏
  final bool payHide;

  /// 选择的科目
  final List<SkuModel> skuList;

  const OrderPaymentPage({
    super.key,
    required this.package,
    required this.index,
    required this.price,
    required this.iosPrice,
    required this.payHide,
    required this.skuList,
    required this.orderModel,
  });

  @override
  State<OrderPaymentPage> createState() => _OrderPaymentPageState();
}

class _OrderPaymentPageState extends State<OrderPaymentPage> {
  late BuildContext _context;

  /// 支付方式
  late PaymentTypeEnum _payIndex;

  @override
  void initState() {
    super.initState();

    if (widget.payHide) {
      _payIndex = PaymentTypeEnum.applypay;
    } else {
      _payIndex = PaymentTypeEnum.alipay;
    }
  }

  @override
  void dispose() {
    super.dispose();

    ToastUtil.loadingBoxRemove();
  }

  @override
  Widget build(BuildContext context) {

    _context = context;
    double bottom = ScreenUtil().bottomBarHeight;
    return Scaffold(
      backgroundColor: colorWhite2,
      body: Column(
        children: [
          PageTitleWidget(name: "订单支付", pageContext: context),
          Expanded(
            child: Column(
              children: [
                Expanded(child: _content()),
                _bottomItems(),
                hiSpace(height: bottom + 30),
              ],
            ),
          ),
        ],
      ),
    );
  }

  /// 底部组件组
  _bottomItems() {
    return Container(

      // height: 176,
      margin: EdgeInsets.symmetric(horizontal: 30),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            "虚拟产品具有较强可复制性，不支持七天无理由退换，如同意请付款",
            style: FontUtil.fontGrey2(18),
          ),
          btnItem(),
        ],
      ),
    );
  }

  /// 按钮组件
  btnItem() {
    String price;
    if (widget.payHide) {
      price = widget.iosPrice.toStringAsFixed(2);
    } else {
      price = widget.price.toStringAsFixed(2);
    }
    return GestureDetector(
      onTap: _onTapFunFk,
      child: Container(
        // width: 690,
        // height: 88,
        padding: EdgeInsets.symmetric(vertical: 10),
        decoration: BoxDecoration(
          color: colorYellow1,
          borderRadius: BorderRadius.circular(49),
        ),
        child: Center(
          child: Text(
            "付款·¥$price",
            style: FontUtil.fontBrown1(28),
          ),
        ),
      ),
    );
  }

  /// 内容显示
  _content() {
    return Container(
      // margin: EdgeInsets.symmetric(horizontal: 30),
      padding: EdgeInsets.symmetric(horizontal: 30),
      child: MediaQuery.removePadding(
        removeTop: true,
        context: _context,
        child: ListView(
          children: [

            hiSpace(height: 20),
            _cardItem(),
            hiSpace(height: 40),
            _selectedItem(),
            hiSpace(height: 40),
            OrderTypeWidget(
              index: _payIndex,
              payHide: widget.payHide,
              // payHide: true,
              onTapFun: _onTapFunZffs,
            ),
            hiSpace(height: 20),
          ],
        ),
      ),
    );
  }

  /// 卡片组件
  _cardItem() {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 0),
      child: PackageCardWidget(
        isBuy: false,
        package: widget.package,
        index: widget.index,
        payHide: widget.payHide,
      ),
    );
  }

  /// 已选科目组件
  _selectedItem() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          "已选科目",
          style: FontUtil.fontBlack1(28, fontWeight: FontWeight.w500),
        ),
        hiSpace(height: 24),
        _labelItems(),
      ],
    );
  }

  /// 显示已选科目的标签
  _labelItems() {
    return Wrap(
      // 主轴方向子widget的间距
      spacing: 30,
      // 纵轴方向的间距
      runSpacing: 30,
      children: widget.skuList
          .map((SkuModel sku) => ShowLabelWidget.order(text: sku.name!))
          .toList(),
    );
  }

  /// 选择支付方式
  _onTapFunZffs(PaymentTypeEnum index) {
    setState(() {
      _payIndex = index;
    });
  }

  /// 付款点击方法
  _onTapFunFk() {
    // Navigator.pushNamed(_context, "/order/pay/success");
    // return;
   // 加载框
    ToastUtil.loadingBoxShow(_context);
    // 判断移动设备
    DeviceTypeEnum deviceTypeEnum = DeviceTypeEnum.android;
    if (Platform.isIOS) {
      deviceTypeEnum = DeviceTypeEnum.ios;
    }
    if (_payIndex == PaymentTypeEnum.alipay) {
      // 支付宝支付
      _alupayOrWeixinPay(
        payFun: _futurePayAlipay,
        deviceTypeEnum: deviceTypeEnum,
      );
    } else if (_payIndex == PaymentTypeEnum.weixin) {
      // 微信支付
      _alupayOrWeixinPay(
        payFun: _futurePayWeixin,
        deviceTypeEnum: deviceTypeEnum,
      );
    } else if (_payIndex == PaymentTypeEnum.applypay) {
      // iOS支付
      _iosPay();
    }
  }

  /// 判断微信/支付宝支付的处理方法
  void _alupayOrWeixinPay({
    required FlutterPayFun payFun,
    required DeviceTypeEnum deviceTypeEnum,
  }) {
    // 支付方法
    payFun(deviceTypeEnum: deviceTypeEnum).then((Map<String, dynamic> map) {
      // 关闭加载框
      ToastUtil.loadingBoxRemove();
      if (map["suc"]) {
        // 加载成功，跳转支付成功页面

        Navigator.pushNamed(_context, "/order/pay/success");
      } else {
        // 发生异常
        ToastUtil.show(context: _context, msg: map["msg"] ?? "未知错误，请重试");
      }
    });
  }

  /// 加载数据方法
  Future<Map<String, dynamic>> _futurePayAlipay({
    required DeviceTypeEnum deviceTypeEnum,
  }) async {
    Map<String, dynamic> map = {};
    try {
      Tobias tobias = Tobias();
      // 验证是否安装了对应应用
      bool result = await tobias.isAliPayInstalled;
      if (!result) {
        return {"suc": false, "msg": "未安装支付宝，请先安装支付宝"};
      }
      // 获取第三方支付签名
      Map<String, dynamic> signData = await PackageDao.paySign(
        type: _payIndex,
        orderId: widget.orderModel.id!,
        paymentChannel: deviceTypeEnum,
      );
      // 调用支付宝，发起支付，
      // 注意：不能使用universalLink返回支付回调，只能使用URL Schemes，
      // fluwx会把所有的universalLink 拦截，Tobias接收不到回调
      var payStr = await tobias.pay(
        signData["body"],
        // universalLink: "https://www.yunxuebao.com/hktkPath/",
      );
      // log("payStr ===> $payStr");
      if (payStr["resultStatus"] == "9000") {
        return {"suc": true, "msg": "支付成功"};
      } else if (payStr["resultStatus"] == "6001") {
        return {"suc": false, "msg": "支付已取消"};
      } else {
        return {"suc": false, "msg": "支付失败"};
      }
      // map = {"suc": true, "msg": "测试"};
    } catch (e) {
      map = {"suc": false, "msg": "未知错误，请重试"};
      if (e is DaoException) {
        map["msg"] = e.msg;
      }
    }
    return map;
  }

  /// 微信支付发起
  Future<Map<String, dynamic>> _futurePayWeixin({
    required DeviceTypeEnum deviceTypeEnum,
  }) async {
    Map<String, dynamic> map = {};
    try {
      Fluwx fluwx = Fluwx();
      // 阻塞异步执行，等待监听回调完成
      Completer<Map<String, dynamic>> wxPayCompleter = Completer();
      // 验证是否安装了对应应用
      bool res = await fluwx.isWeChatInstalled;
      if (!res) {
        return {"suc": false, "msg": "未安装微信，请先安装微信"};
      }
      // 获取第三方支付签名
      Map<String, dynamic> signData = await PackageDao.paySign(
        type: _payIndex,
        orderId: widget.orderModel.id!,
        paymentChannel: deviceTypeEnum,
      );
      // 监听返回数据
      // 监听返回
      FluwxCancelable? cancel;
      cancel = fluwx.addSubscriber((event) {
        if (event is! WeChatPaymentResponse) {
          map["suc"] = false;
          return;
        }
        cancel?.cancel();
        if (event.errCode == 0) {
          // 支付成功
          map["suc"] = true;
        } else if (event.errCode == -1) {
          map["suc"] = false;
          map["msg"] = "支付错误,${event.errStr}";
        } else if (event.errCode == -2) {
          map["suc"] = false;
          map["msg"] = "支付已取消";
        } else {
          map["suc"] = false;
          map["msg"] = "支付失败";
        }
        wxPayCompleter.complete(map);
      });
      // 发起支付
      await fluwx.pay(
        which: Payment(
          appId: signData['appid'],
          partnerId: signData['partnerid'],
          prepayId: signData['prepayid'],
          packageValue: signData['package'],
          nonceStr: signData['noncestr'],
          timestamp: int.parse(signData['timestamp']),
          sign: signData['sign'],
        ),
      );
      return wxPayCompleter.future;
      // map = {"suc": true, "msg": "sssss"};
    } catch (e) {
      map = {"suc": false, "msg": "未知错误，请重试"};
      if (e is DaoException) {
        map["msg"] = e.msg;
      }
    }
    return map;
  }

  /// iOS支付方法
  _iosPay() {
    // 初始化
    BuyIOSUtil buyIOSUtil = BuyIOSUtil();

    // 开始支付
    buyIOSUtil.doIOSPay(
      orderId: widget.orderModel.id!,
      iosPrice: widget.iosPrice,
      onConnectAppStore: () {
      },
      onSuccess: () {
        ToastUtil.loadingBoxRemove();
        // 发送苹果回调
        PackageDao.applySuccessNotify(orderId: widget.orderModel.id!);
        // 加载成功，跳转支付成功页面
        // NavigatorUtil.pushToPay(_context);
        Navigator.pushReplacement(
          context,
          MaterialPageRoute(
            builder: (context) => const PaySuccessPage(),
            settings: const RouteSettings(
              name: "PaySuccessPage",
            ),
          ),
        );
      },
      onError: (String res) {
        ToastUtil.loadingBoxRemove();
        ToastUtil.show(context: _context, msg: res);
      },
    );
  }
}
